package demo2;

public class MyLinkedList {

    /**
     * 从尾巴入队O(1)，从头出O(1)
     * 单链表实现队列
     */
    class Node {
        public int val;
        public Node next;

        public Node(int val) {
            this.val = val;
        }
    }

    public Node head;
    public Node last;
    public int usedSize;

    public void offer(int val) {
        Node node = new Node(val);

        if (this.head == null) {
            head = node;
            last = node;
        }else {
            last.next = node;
            last = node;
        }
        usedSize++;
    }

    public int peek() {
        if (this.head == null) {
            throw new RuntimeException();
        }

        return this.head.val;
    }

    public int poll() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空");
        }

        int val = head.val;
        head = head.next;
        if (head == null) {
            last = null;
        }
        usedSize--;
        return val;
    }

    public int size() {
//        int count = 0;
//
//        Node cur = this.head;
//        while (cur != null) {
//            count++;
//            cur = cur.next;
//        }
//        return count;

        return usedSize;
    }

    public boolean isEmpty() {
//        if (head == null) {
//            return true;
//        }
//        return false;

        return usedSize == 0;
    }
}
